<template>
  <div class="updategoods">
      <qwerty title1='商品管理' title2='修改商品'></qwerty>
      <el-card style="margin-top:20px">
         <el-alert
    title="商品修改"
    type="info"
    center
    show-icon
    :closable="false">
  </el-alert>
   <el-form :model="ruleForm" :rules="rules" ref="addForm" label-width="100px" label-position="top" class="demo-ruleForm">
          <el-steps :active="active-0" finish-status="success" style="width: 90%;margin:10px auto">
             <el-step title="基本信息">基本信息</el-step>
             <el-step title="商品参数">商品参数</el-step>
             <el-step title="商品属性">商品属性</el-step>
             <el-step title="商品图片">商品图片</el-step>
             <el-step title="商品内容">商品内容</el-step>
             <el-step title="完成">完成</el-step>
           </el-steps>
           <el-tabs @tab-click="handleClick" v-model="active" :tab-position="tabPosition" :before-leave="beforeTableave" style="margin-top:20px">
             
                  <el-tab-pane label="基本信息" name="0">
                  
                      <el-form-item label="商品名称" prop="goods_name">
                        <el-input v-model="ruleForm.goods_name"></el-input>
                      </el-form-item>
                      <el-form-item label="商品价格" prop="goods_price">
                        <el-input type="number" v-model="ruleForm.goods_price"></el-input>
                      </el-form-item>
                      <el-form-item label="商品重量" prop="goods_weight">
                        <el-input type="number" v-model="ruleForm.goods_weight"></el-input>
                      </el-form-item>
                      <el-form-item label="商品数量" prop="goods_number">
                        <el-input type="number" v-model="ruleForm.goods_number"></el-input>
                      </el-form-item>
                      <!-- <el-form-item label="商品分类" prop="goods_cat">
                        <el-cascader
                          v-model="ruleForm.goods_cat"
                          :props="cascaderProps"
                          :options="options"
                          @change="handleChange">
                        </el-cascader>
                      </el-form-item> -->
                  </el-tab-pane>
              <!-- <el-tab-pane label="商品参数" name="1">
                <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
                  <el-checkbox-group v-model="item.attr_vals">
                    <el-checkbox border :label="cb" v-for="(cb,i) in item.attr_vals" :key="i">
                    </el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-tab-pane>
              <el-tab-pane label="商品属性" name="2">
                <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.id">
                  <el-input v-model="item.attr_vals"></el-input>
                </el-form-item>
              </el-tab-pane> -->
              <el-tab-pane label="商品图片" name="2">
                <el-upload
                  class="upload-demo"
                  :action="uploadUrl"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :headers="headersObj"
                  :on-success="handleSuccess"
                  :file-list="fileList"
                  list-type="picture">
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
                 
              </el-tab-pane>
              <el-tab-pane label="商品内容" name="3">
                <quill-editor style="height:200px" v-model="ruleForm.goods_introduce">
                </quill-editor>
                <el-button type="primary" style="margin-top:80px" @click="add('addForm')">修改商品</el-button>
              </el-tab-pane>
          </el-tabs>
      </el-form>
      </el-card>
      <el-dialog
  title="查看图片"
  :visible.sync="previewVisible"
  width="30%"
  :before-close="handleClose">
  <span>
    <img width="100%" :src="previewPath" alt="">
  </span>
  <span slot="footer" class="dialog-footer">
    <el-button @click="previewVisible = false">取 消</el-button>
    <el-button type="primary" @click="previewVisible = false">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
import {getCategories} from '@/api/cate2'
import {getParams,addGoods,getGoodsById,updateGoods} from '@/api/goods'
import _ from 'lodash'
export default {
    name:'addgoods',
    data() {
      return {
        fileList:[],
        headersObj:{
          Authorization:window.sessionStorage.getItem('token')
        },
        uploadUrl:"http://122.112.253.28:8888/api/private/v1/upload",
         cascaderProps:{
          value:'cat_id',
          label:'cat_name',
          children:'children',
          expandTrigger: 'hover'
        },
        options:[],
        ruleForm: {
          goods_name: '',//商品名称
          goods_cat:[],//价格
          goods_price:0,//价格
          goods_number:0,//数量
          goods_weight:0,//重量
          goods_introduce:'',//介绍
          pics:[],//上传的图片临时路径（对象）
        //   goods_cat: [],//以为','分割的分类列表
          attrs:[]//商品的参数（数组），包含 `动态参数` 和 `静态属性`
        },
        rules: {
          goods_name: [
            { required: true, message: '请输入商品名称', trigger: 'blur' }
          ],
          goods_price: [
            { required: true, message: '请选择价格', trigger: 'blur' }
          ],
          goods_number: [
            { required: true, message: '请选择数量', trigger: 'blur' }
          ],
          goods_weight: [
            { required: true, message: '请选择重量', trigger: 'blur' }
          ],
          goods_cat: [
            { required: true, message: '请选择分类', trigger: 'blur' }
          ]
        },
          tabPosition: 'left',
          active: 0,
          queryInfo:{
          type:3,
          pagenum:1,
          pagesize:8
        },
        cateId:'',
        manyTableData:[],
        onlyTableData:[],
        previewPath:'',
        previewVisible:false
      };
    },
    methods: {
      beforeTableave(activeName,oldActiveName){
        if(oldActiveName==='0'){
         this.$refs.addForm.validate(async valid=>{
             if(!valid){
                 this.$message.error('请填写必要的表单项！');  
                return false;
             }
          })
        }
      },
      async add(addForm){
        this.$refs[addForm].validate(async valid=>{
          if(!valid) return this.$message.error('请填写必要的表单项！');
          
        //   this.ruleForm.goods_cat=this.ruleForm.goods_cat.join(',');
        //   alert(this.ruleForm.goods_cat)
          
        //   this.manyTableData.forEach(item=>{
        //     const newInfo={
        //       attr_id:item.attr_id,
        //       attr_value:item.attr_vals.join(' ')
        //     }
        //     this.ruleForm.attrs.push(newInfo)
        //   })

        //   this.onlyTableData.forEach(item=>{
        //     const newInfo={
        //       attr_id:item.attr_id,
        //       attr_value:item.attr_vals
        //     }
        //     this.ruleForm.attrs.push(newInfo)
        //   })
          // var form=new FormData();
          // form.attrs=this.addForm.attrs
          // console.log(this.ruleForm)

          var {data:res} =await updateGoods(`goods/${this.$route.params.id}`,this.ruleForm);
          if(res.meta.status==200){
            this.$message.success(res.meta.msg)
            this.$router.push('/goods');
          }else{
            this.$message.error(res.meta.msg)
            this.$router.push('/goods');
          }
        })
      },
      handleSuccess(response){
        const picInfo={pic:response.data.tmp_path}
        this.ruleForm.pics.push(picInfo)
        console.log(this.ruleForm)
      },
       handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      handleRemove(file) {
        const filePath=file.response.data.tem_path
        const i =this.ruleForm.pics.findIndex(x=>x.pic===filePath)
        this.ruleForm.pics.splice(i,1);
        console.log(this.ruleForm)
      },
      handlePreview(file) {
        console.log(file)
        this.previewPath=file.url
        this.previewVisible=true;
      },
      async  handleChange(){
        this.cateId=this.ruleForm.goods_cat[
          this.ruleForm.goods_cat.length-1
        ]
      },
    //  async select(){
    //     var {data:res} =await getCategories(this.queryInfo);
    //     this.options=res.data.result;
    //   },
      async changeInput(){
        var {data:res} =await getGoodsById('goods/'+this.$route.params.id);
        this.ruleForm.goods_id=res.data.goods_id
        this.ruleForm.goods_name=res.data.goods_name
        this.ruleForm.goods_cat=res.data.goods_cat
        this.ruleForm.goods_price=res.data.goods_price
        this.ruleForm.goods_number=res.data.goods_number
        this.ruleForm.goods_weight=res.data.goods_weight
        this.ruleForm.goods_introduce=res.data.goods_introduce
        this.ruleForm.pics=res.data.pics
        this.ruleForm.attrs=res.data.attrs
        console.log(res);
        this.ruleForm.pics.forEach(item=>{
            const newImg={
                url:item.pics_big_url
            }
            this.fileList.push(newImg)
        })
        
      },
      async handleClick() {
        if(this.active=='1'){
          const {data:res} =await getParams(`categories/${this.cateId}/attributes`,{
            sel:'many'
          })
          // alert(res.data[0].attr_vals)
          res.data.forEach((item)=>{
            item.attr_vals=item.attr_vals.length===0?[]:item.attr_vals.split(' ');
            
            console.log(item)
          })
          this.manyTableData=res.data
        }else if(this.active=='2'){
           const {data:res} =await getParams(`categories/${this.cateId}/attributes`,{
            sel:'only'
          })
          this.onlyTableData=res.data
        }
      }
    },
    created(){
      this.changeInput();
    //   this.select();
    }
}
</script>

<style>

</style>